package com.cloudcc.mobile.view.main.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.cloudframe.bus.DataEvent;
import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.EventList.UpdateUserEvent;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.cloudframe.bus.MenuToggleEvent;
import com.cloudcc.cloudframe.model.UserModel;
import com.cloudcc.cloudframe.util.PackageUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.db.DraftBoxDB;
import com.cloudcc.mobile.db.MessageDB;
import com.cloudcc.mobile.entity.ChatUser;
import com.cloudcc.mobile.entity.Message;
import com.cloudcc.mobile.entity.UserBasicInfoForUpdate;
import com.cloudcc.mobile.entity.chat.DraftBox;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.presenter.ContactPresenter;
import com.cloudcc.mobile.util.ImageUtils;
import com.cloudcc.mobile.util.NotificationUtils;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.util.UserUtils;
import com.cloudcc.mobile.view.activity.CloudccActivity;
import com.cloudcc.mobile.view.activity.DraftBoxActivity;
import com.cloudcc.mobile.view.activity.DraftBoxGetDataActivity;
import com.cloudcc.mobile.view.activity.Myinformation;
import com.cloudcc.mobile.view.main.MainUIActivity;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.litesuits.android.async.Log;
import com.mypage.utils.NetStateUtils;
import com.mypage.utils.SaveTemporaryData;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.pgyersdk.update.PgyUpdateManager;
import com.pgyersdk.update.UpdateManagerListener;
import com.pgyersdk.update.javabean.AppBean;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class Newmainmefragments extends Fragment implements IContactUserInfo, IEventLife {

	/**
	 * By liuyongjie 2017-07-12
	 */
	@Bind(R.id.caogao_timetext)
	TextView caogaotime;
	@Bind(R.id.caogaoxiang_chat)
	LinearLayout caogaoxiang;
	@Bind(R.id.caogaonum)
	TextView caogaonum;
	@Bind(R.id.caogao_text)
	TextView caogaotext;
	@Bind(R.id.systemmes_chat)
	LinearLayout systemmes;
	@Bind(R.id.timetext)
	TextView timetext;
	@Bind(R.id.systemmessnum)
	TextView messagenum;
	@Bind(R.id.message_text)
	TextView messagetext;
	private Context context;
	private MessageDB db;
	private DraftBoxDB db2;

	/**
	 * 一下是ta人写的代码
	 */
    @Bind(R.id.message_num_tz)
    TextView message_num_tz;
    @Bind(R.id.message_num_99)
    TextView message_num_99;
	private RelativeLayout ll1,ll4, ll5;//1是关于cloudcc，4是设置 5是注销
	private LinearLayout  ll3, chat_userinfo;//ll3演示
	private RelativeLayout ll2;
	private TextView user_name, user_company;
	private ImageView user_follow;
	private ContactPresenter mContactPresenter;
	//	protected Context mContext;
	private ChatUser user;
	private RelativeLayout relaxinxi;
	public Bitmap imgphoto ;
	public ImageView allmenubtn;
	public FrameLayout updatelayout;
	private String mEns = RunTimeManager.getInstance().getlanguage();
	@Override
	public View onCreateView(LayoutInflater inflater,
							 @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.newmainme, container, false);
		ButterKnife.bind(this, view);
		context = getActivity();
		initDb();
		mContactPresenter = new ContactPresenter((IContactUserInfo) Newmainmefragments.this);
		updatelayout = (FrameLayout) view.findViewById(R.id.updatelayout);
		allmenubtn = (ImageView) view.findViewById(R.id.allmenubtn);
		ll1 = (RelativeLayout) view.findViewById(R.id.linearguanyu);
		ll2 = (RelativeLayout) view.findViewById(R.id.linearjiance);
		ll3 = (LinearLayout) view.findViewById(R.id.linearyanshi);
		ll4 = (RelativeLayout) view.findViewById(R.id.linearshezhi);
		ll5 = (RelativeLayout) view.findViewById(R.id.linearzhuxiao);
		relaxinxi = (RelativeLayout) view.findViewById(R.id.chat_me_info);
		chat_userinfo = (LinearLayout) view.findViewById(R.id.chat_userinfo);//所有的添加背景的地方
		user_name = (TextView) view.findViewById(R.id.user_name);
		user_company = (TextView) view.findViewById(R.id.user_company);
		user_follow = (ImageView) view.findViewById(R.id.user_follow);

        addlistener();
		register();
		initData();
//		initBackground();
		try {
			setMessageNum();
		} catch (DbException e) {
			e.printStackTrace();
		}
		return view;
	}
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (!NetStateUtils.isNetworkConnected(getActivity())){
			Toast.makeText(getActivity(), R.string.zanwus,Toast.LENGTH_SHORT).show();
		}
		refreshUserInfoFromNet();
//		checjUpdata();
//		initNewVersion();
		MessageSetNCL();
//		refreshLogo();
	}

	private void initNewVersion(){
		new PgyUpdateManager.Builder()
				.setForced(false)                //设置是否强制更新,非自定义回调更新接口此方法有用
				.setUserCanRetry(false)         //失败后是否提示重新下载，非自定义下载 apk 回调此方法有用
				.setDeleteHistroyApk(false)     // 检查更新前是否删除本地历史 Apk
				.setUpdateManagerListener(new UpdateManagerListener() {
					@Override
					public void onNoUpdateAvailable() {
						//没有更新是回调此方法
						android.util.Log.d("pgyer", "there is no new version");
						if ("en".equals(mEns)) {
							Toast.makeText(getActivity(), "There is no latest version", Toast.LENGTH_LONG).show();
						} else {
							Toast.makeText(getActivity(), "没有最新版本", Toast.LENGTH_LONG).show();
						}
					}

					@Override
					public void onUpdateAvailable(AppBean appBean) {
						//更新是回调此方法
						android.util.Log.d("pgyer", "there is new version can update"
								+ "new versionCode is " + appBean.getVersionCode());
						if ("en".equals(mEns)) {
							showUpdateDialog(getActivity(), "check for updates", "jump to download the latest version?");
						} else {
							showUpdateDialog(getActivity(), "检查更新", "确认跳转去下载最新版本么？");
						}
					}


					@Override
					public void checkUpdateFailed(Exception e) {
						//更新检测失败回调
						android.util.Log.e("pgyer", "check update failed ", e);
						if ("en".equals(mEns)) {
							Toast.makeText(getActivity(), "There is no latest version", Toast.LENGTH_LONG).show();
						} else {
							Toast.makeText(getActivity(), "没有最新版本", Toast.LENGTH_LONG).show();
						}
					}
				}).register();
	}

//	public void checjUpdata() {
//
//		final int versionCode = PackageUtils.getVersionCode(getActivity());
//		String versionName = PackageUtils.getVersionName(getActivity());
//		HttpUtils utils = new HttpUtils();
//		utils.send(HttpMethod.GET, UrlManager.gengxin,
//				new RequestCallBack<String>() {
//
//					@Override
//					public void onFailure(HttpException arg0, String arg1) {
//						Log.d("-------------------------", "Failure。。。"
//								+ arg1);
//					}
//
//					@Override
//					public void onSuccess(ResponseInfo<String> arg0) {
//						String result = arg0.result;
//						Log.d("-------------------------",
//								"Success_down:     " + result);
//						if (Integer.valueOf(result) > versionCode) {
//							updatelayout.setVisibility(View.VISIBLE);
//							setListener();
//						} else {
//							updatelayout.setVisibility(View.GONE);
//							noUpdata();
//						}
//					}
//
//				});
//
//	}

	private void noUpdata() {
		// TODO Auto-generated method stub
	}

	@OnClick(R.id.mess_right)
	public void onClickRight(){
		EventEngine.post(new MenuToggleEvent(false, true));
	}
	public void setListener() {
		// 检测更新
		ll2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				final int versionCode = PackageUtils.getVersionCode(getActivity());
				String versionName = PackageUtils.getVersionName(getActivity());
				HttpUtils utils = new HttpUtils();
				utils.send(HttpMethod.GET, UrlManager.gengxin,
						new RequestCallBack<String>() {

							@Override
							public void onFailure(HttpException arg0, String arg1) {
								Log.d("-------------------------", "Failure。。。" + arg1);
							}

							@Override
							public void onSuccess(ResponseInfo<String> arg0) {
								String result = arg0.result;
								Log.d("-------------------------", "Success_down:     " + result);
								if (Integer.valueOf(result) > versionCode) {
									if ("en".equals(mEns)) {
										showUpdateDialog(getActivity(), "check for updates", "jump to download the latest version?");
									} else {
										showUpdateDialog(getActivity(), "检查更新", "确认跳转去下载最新版本么？");
									}

								}
							}
						});
			}
		});
	}

	private void addlistener() {
		allmenubtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				EventEngine.post(new MenuToggleEvent(false, false));
			}
		});

		// TODO Auto-generated method stub
		relaxinxi.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
//				Toast.makeText(getActivity(), "点击头像信息", 1).show();
				UserBasicInfoForUpdate userBasicInfoForUpdate = new UserBasicInfoForUpdate();
//				Intent intent = new Intent(mContext, UpdateInfoActivity.class);
//				Intent intent = new Intent(getActivity(), NeweditorActivity.class);
				Intent intent = new Intent(getActivity(), Myinformation.class);
				SaveTemporaryData.mSmart = "";
                SaveTemporaryData.detailDyamic="";
				SaveTemporaryData.GeneralOne = false;
				userBasicInfoForUpdate.setEmail(user.getEmail() + " ");
				userBasicInfoForUpdate.setMobile(user.getMobile());
				userBasicInfoForUpdate.setPhone(user.getPhone());
//				userBasicInfoForUpdate.setTitle(user.getTitle());
//				userBasicInfoForUpdate.setAddress(user.getAddress());
//				userBasicInfoForUpdate.setAbout(user.getAboutme());
//				userBasicInfoForUpdate.setImg(user.getImg());
				userBasicInfoForUpdate.setName(user.getName());
				userBasicInfoForUpdate.userId = user.getUserid();
//				userBasicInfoForUpdate.setImgphoto(imgphoto);
				intent.putExtra("chatuser", userBasicInfoForUpdate);//
				intent.putExtra("isme", "me");
				intent.putExtra("Ownoneself","YES");

//				try {
//					ByteArrayOutputStream baos = new ByteArrayOutputStream();
//					((MainUIActivity) getActivity()).imgphoto.compress(Bitmap.CompressFormat.PNG, 100, baos);
//					byte[] bytes=baos.toByteArray();
//
//					Bundle b = new Bundle();
//					b.putByteArray("bitmap", bytes);
//					intent.putExtras(b);
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
				startActivityForResult(intent, 001);
			}
		});
		// 关于cloudcc
		ll1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
//				Toast.makeText(getActivity(), "点击关于cloudcc", 1).show();
				Intent intent = new Intent(getActivity(), CloudccActivity.class);
				startActivity(intent);
			}
		});


		// 进入演示
		ll3.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast.makeText(getActivity(), "点击 进入演示", Toast.LENGTH_LONG).show();
			}
		});
		// 设置
		ll4.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
//				Toast.makeText(getActivity(), "点击设置", 1).show();


				SharedPreferences sp = getActivity().getSharedPreferences("jump", 0);
				SharedPreferences.Editor editor = sp.edit();
				editor.clear();
				editor.putString("mBacks", "backs");
				editor.commit();
				((MainUIActivity) getActivity()).menu_foot.setVisibility(View.GONE);
				((MainUIActivity) getActivity()).tabSelect(5);
			}
		});
		// 注销账号
		ll5.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
//				// TODO Auto-generated method stub
//				Toast.makeText(getActivity(), "点击注销账号", 1).show();
				((MainUIActivity) getActivity()).showClearLogin(null);
			}
		});


		ll2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				initNewVersion();
			}
		});
	}

	public void showUpdateDialog(final Context context, String title,
								 String message) {
		/**
		 * 自定义的dialog
		 */
		final AlertDialog builder = new AlertDialog.Builder(context).create();
		builder.setCancelable(false);
		View view = LayoutInflater.from(context)
				.inflate(R.layout.zhuxiao, null);
		builder.setView(view);
		builder.show();
		Button queren = (Button) view.findViewById(R.id.queren);
		Button quxiao = (Button) view.findViewById(R.id.quxiao);
		TextView titleName = (TextView) view.findViewById(R.id.titlename);
		TextView bodyName = (TextView) view.findViewById(R.id.bodyname);
		titleName.setText(title);
		bodyName.setText(message);
		queren.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Uri uri = Uri.parse("https://www.pgyer.com/q3PD");
				Intent it = new Intent(Intent.ACTION_VIEW, uri);
				startActivity(it);
			}
		});
		quxiao.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				builder.cancel();
			}
		});
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 001 && resultCode == Activity.RESULT_OK) {
			initData();
		}
	}

	/**
	 * 初始化数据
	 */
	private void initData() {
		refreshUserfromCache();
		refreshUserInfoFromNet();
	}

	/**
	 * 根据缓存的数据显示
	 */
	private void refreshUserfromCache() {
		UserModel usermodel = UserManager.getManager().getUser();
		ChatUser chatUser = new ChatUser();
		String zero = String.valueOf(0);
		chatUser.setCommentednum(zero);
		chatUser.setPhone(usermodel.phone);
		chatUser.setFeedandcomnum(zero);
		chatUser.setPraisenum(zero);
		chatUser.setTitle(usermodel.roleName);
		chatUser.setEmail(usermodel.email);
		chatUser.setName(usermodel.userName);
		chatUser.setLastModifyDate(zero);
		chatUser.setCreateDate(zero);
		chatUser.setMobile(usermodel.mobilePhone);
		chatUser.setAddress("");
		chatUser.setAboutme("");
		user = chatUser;
		Log.d("userdata", usermodel.email + "::" + usermodel.mobilePhone + "::" + usermodel.userName);
		refreshUIAndData();
	}

	/**
	 * 背景
	 */
//	private void initBackground() {
//		String aa = getActivity().getCacheDir().getAbsolutePath() + File.separator + UserManager.getManager().getUser().userId + ".png";
//		Bitmap bitmap = ImageUtils.getBitmap(aa);
//		if (bitmap != null) {
//			chat_userinfo.setBackgroundDrawable(new BitmapDrawable(bitmap));
//		}
//
//
//	}

	/**
	 * 刷新用户
	 */
	private void refreshUserInfoFromNet() {
		mContactPresenter.getUserInfoChatter(UserManager.getManager().getUser().userId);

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		unRegister();
	}

	@Override
	public void register() {
		EventEngine.register(this);
	}

	@Override
	public void unRegister() {
		EventEngine.uregister(this);
	}

	@Override
	public void onGettedUser(DataEvent<ChatUser> event) {
		// TODO Auto-generated method stub
		if (event.isError()) {
			return;
		}
		user = event.getData();
		refreshUIAndData();
	}

	private void refreshUIAndData() {
		refreshLogo();
		// 容器
//		user_attr_container.setVisibility(View.VISIBLE);

		// 关于
		user_name.setText(user.getName());
		user_company.setText(user.getEmail());
		SaveTemporaryData.mUserName = user.getName();
	}

	/**
	 * 头像切换成功
	 *
	 * @param event
	 */
	int isshuaxinlogo = 1;//判断是否刷新logo
	public void onEventMainThread(UpdateUserEvent event) {
		Bitmap imgphoto = ((MainUIActivity) getActivity()).imgphoto;
		this.imgphoto = imgphoto;
        isshuaxinlogo = 2;
		user_follow.setImageBitmap(imgphoto);
	}

	private void refreshLogo() {

		try {
            if(isshuaxinlogo==1){

			String userId = UserManager.getManager().getUser().userId;
			String url = UrlTools.getTopImage(userId);
			UserUtils.setLogoRound_z(url, user_follow,
					UserUtils.getBackGroudColorByUserIdHash(userId, getActivity()),
					UserUtils.getNickRowName(user.getName()), getActivity());

			imgphoto =ImageUtils.toRoundBitmap(UserManager.getManager().getLogo());
			user_follow.setImageBitmap(imgphoto);
            }else{

            }

		}catch (Exception ex){

		}

	}

	private DisplayImageOptions getUserLogoDisplayImageOptions() {
		DisplayImageOptions displayImageOptions = new DisplayImageOptions.Builder()
				.bitmapConfig(Bitmap.Config.RGB_565)
				.imageScaleType(ImageScaleType.EXACTLY)// default
				.build();
		return displayImageOptions;
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		ButterKnife.unbind(this);
	}


	public void initDb() {
		UserModel user = UserManager.getManager().getUser();
		db = new MessageDB(context, user.userId + "message");
		db2 = new DraftBoxDB(context, user.userId + "box.db");
	}

	//--------------------------------
	private void setMessageNum() throws DbException {

		// 设置消息数量

		long messnum = db.getNewMessageNum();
		long draftnum = db2.getNewDraftBoxNum();
		AppContext.mesnum = (int) messnum;


		// 设置消息的数量显示
		if (messnum > 0) {
//			messagenum.setVisibility(View.VISIBLE);
			if (messnum > 99) {
				messagenum.setText("99");
			} else {
				messagenum.setText("" + messnum);
			}
		} else {
			messagenum.setVisibility(View.INVISIBLE);
		}
		Message mes = db.getLastMessage();
		if (mes != null) {
//			timetext.setVisibility(View.VISIBLE);
//			messagetext.setVisibility(View.VISIBLE);
			timetext.setText(mes.getTime());
			messagetext.setText(mes.getContext());
		} else {
			timetext.setVisibility(View.INVISIBLE);
			if ("en".equals(mEns)) {
				messagetext.setText("No news");
			} else {
				messagetext.setText("暂无消息");
			}

		}
		// 设置草稿箱的数量显示
		if (draftnum > 0) {
//			caogaonum.setVisibility(View.VISIBLE);
			if (draftnum > 99) {
				caogaonum.setText("99");
			} else {
				caogaonum.setText("" + draftnum);
			}
		} else {
			caogaonum.setVisibility(View.INVISIBLE);
		}
		DraftBox box = db2.getLastDraftBox();
		if (box != null) {
//			caogaotime.setVisibility(View.VISIBLE);
//			caogaotext.setVisibility(View.VISIBLE);
            caogaotext.setVisibility(View.INVISIBLE);
			caogaotime.setText(box.getTime());
			String a = box.getType();

			if (a.equals("1")) {
				if ("en".equals(mEns)) {
					caogaotext.setText("Check in");
				} else {
					caogaotext.setText("签到");
				}

			} else if (a.equals("2")) {
				if ("en".equals(mEns)) {
					caogaotext.setText("Micro-paste");
				} else {
					caogaotext.setText("微贴");
				}

			} else if (a.equals("3")) {
				if ("en".equals(mEns)) {
					caogaotext.setText("Reply");
				} else {
					caogaotext.setText("回复");
				}

			}
		} else {
			caogaotime.setVisibility(View.INVISIBLE);
			if ("en".equals(mEns)) {
				caogaotext.setText("no content yet");
			} else {
				caogaotext.setText("暂无内容");
			}

		}


	}

	@OnClick({R.id.caogaoxiang_chat, R.id.systemmes_chat})
	public void onClick(View view) {
		switch (view.getId()) {
			case R.id.caogaoxiang_chat:
				Intent intent = new Intent(getActivity(), DraftBoxActivity.class);
				startActivity(intent);


				break;
			case R.id.systemmes_chat:

				try {
					if (db.isExit()) {
						db.clearMessageNum();
					}
				} catch (DbException e) {
					Tools.handle(e);
				}
				NotificationUtils.clearNotification(getActivity(), 2000);
				Intent messageNum = new Intent(AppContext.MESSAGE_SYSTEM_NUM);
				getActivity().sendBroadcast(messageNum);
//				Intent intenta = new Intent(getActivity(), MessageActivity.class);
				Intent intenta = new Intent(getActivity(), DraftBoxGetDataActivity.class);
				startActivity(intenta);
				break;
		}

	}

    public void MessageSetNCL(){
        long messagenum = 0;
        messagenum= RunTimeManager.getInstance().getMessageNx();
        message_num_tz.setText(messagenum+"");
        if(messagenum>0) {
            message_num_tz.setVisibility(View.VISIBLE);
            if(messagenum>99) {
                message_num_tz.setVisibility(View.INVISIBLE);
                message_num_99.setVisibility(View.VISIBLE);
            }

        }else {
            message_num_tz.setVisibility(View.INVISIBLE);
            message_num_99.setVisibility(View.INVISIBLE);
        }

    }
    }

